package com.itheima.book.dao;
//完成数据增删操作，供Service层调用

import com.itheima.book.domain.Book;

public class BookDao implements BookBaseDao {

    //创建一个数组对象
    private Book[] books = new Book[5];

    //定义方法(addBook)将BookService传递过来图书信息存储到数组中

    public boolean addBook(Book book) {
        //1. 获取数组元素为null的索引值
        int index = -1;
        for (int i = 0; i < books.length; i++) {
            if (books[i] == null) {
                index = i;
                //2. 将Book数据存储到该索引位置
                books[i] = book;
                break;
            }
        }
        //3. 如果数组已经存满返回false
        if (index != -1) {
            return true;
        }
        return false;
    }

    //定义一个获取所有图书信息的方法
    public Book[] allBooks() {
        return books;
    }

    //定义删除图书的方法(deleteByBookId)
    public void deleteByBookId(String bookId) {
        //遍历数组获取每一个图书对象，判断当前图书对应的id是否与要删除的图书对象的id相同
        for (int i = 0; i < books.length; i++) {
            if (books[i] != null) {
                if (books[i].getBookId().equals(bookId)) {
                    books[i] = null;
                    break;
                }
            }
        }
    }

    //定义修改图书的方法(updateBookByBookId),接收BookController传递过来的图书数据
    public void updateBookByBookId(Book book) {
        //2. 遍历books数组，获取每一个book数据，然后判断当前遍历的book对象的bookId是否和传递过来的bookId相同
        for (int i = 0; i < books.length; i++) {
            if (books[i] != null) {
                //3. 如果相同，就将传递过来的book对象赋值给该索引处的元素
                if (books[i].getBookId().equals(book.getBookId())) {
                    books[i] = book;
                    break;
                }
            }
        }
    }
}
